package org.xqh.study.leetcode.algorithm.mineffort;


import java.util.*;

/**
 * @ClassName MinimumEffortPath2
 * @Description 官方题解
 * @Author xuqianghui
 * @Date 2021/2/1 16:48
 * @Version 1.0
 */
public class MinimumEffortPath2 {

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[][] heights = {{1,2,2},{3,8,2},{5,3,5}};
        int ret = solution.minimumEffortPath(heights);
        System.out.println(ret);
    }

    public static class Solution {
        public int minimumEffortPath(int[][] heights) {
            int m = heights.length;//行数
            int n = heights[0].length;//列数
            List<int[]> edges = new ArrayList<int[]>();
            for (int i = 0; i < m; ++i) {
                for (int j = 0; j < n; ++j) {
                    int id = i * n + j;//组合 表格序号
                    if (i > 0) {// 大于第一行
                        edges.add(new int[]{id - n, id, Math.abs(heights[i][j] - heights[i - 1][j])});
                    }
                    if (j > 0) {// 大于第一列
                        edges.add(new int[]{id - 1, id, Math.abs(heights[i][j] - heights[i][j - 1])});
                    }
                }
            }
            //按 高度差 做排序
            Collections.sort(edges, new Comparator<int[]>() {
                public int compare(int[] edge1, int[] edge2) {
                    return edge1[2] - edge2[2];
                }
            });

            UnionFind uf = new UnionFind(m * n);
            int ans = 0;//最小路径
            for (int[] edge : edges) {
                int x = edge[0], y = edge[1], v = edge[2];
                uf.unite(x, y);
                if (uf.connected(0, m * n - 1)) {
                    ans = v;
                    break;
                }
            }
            return ans;
        }
    }

    // 并查集模板
  public static   class UnionFind {
        int[] parent;
        int[] size;
        int n;
        // 当前连通分量数目
        int setCount;

        public UnionFind(int n) {
            this.n = n;
            this.setCount = n;
            this.parent = new int[n];
            this.size = new int[n];
            Arrays.fill(size, 1);
            for (int i = 0; i < n; ++i) {
                parent[i] = i;
            }
        }

        public int findset(int x) {
            return parent[x] == x ? x : (parent[x] = findset(parent[x]));
        }

        public boolean unite(int x, int y) {
            x = findset(x);
            y = findset(y);
            if (x == y) {
                return false;
            }
            if (size[x] < size[y]) {
                int temp = x;
                x = y;
                y = temp;
            }
            parent[y] = x;
            size[x] += size[y];
            --setCount;
            return true;
        }

        public boolean connected(int x, int y) {
            x = findset(x);
            y = findset(y);
            return x == y;
        }
    }
}
